///////////////////////////////////////////////////////////////////////////

#ifndef _MP3TRACK_H_
#include "mp3track.h"
#endif

///////////////////////////////////////////////////////////////////////////

#include <cassert>

///////////////////////////////////////////////////////////////////////////

bool MP3Track::m_Inited = false;

///////////////////////////////////////////////////////////////////////////


void MP3Track::Init()
{
    if (mpg123_init() != MPG123_OK)
    {
        assert(0);
        throw "MPG123 failed to init";
    }

    m_Inited = true;
}


///////////////////////////////////////////////////////////////////////////


MP3Track::MP3Track( const std::string& _fileName )
{
    // Init mpg123 library
    if (!m_Inited)
        Init();

    int err;
    m_FileHandle = mpg123_new(NULL, &err);
    if (!m_FileHandle || err != MPG123_OK)
        return;

    /* Let mpg123 work with the file, that excludes MPG123_NEED_MORE messages. */
    err = mpg123_open( m_FileHandle, _fileName.c_str() );
    if (err != MPG123_OK)
        return;

    /* Peek into track and get first output format. */
    err = mpg123_getformat(m_FileHandle, &m_Rate, &m_Channels, &m_Encoding);
    if (err != MPG123_OK)
        return;
}


///////////////////////////////////////////////////////////////////////////


MP3Track::~MP3Track()
{
    if (m_FileHandle)
        mpg123_close(m_FileHandle);
}


///////////////////////////////////////////////////////////////////////////


bool MP3Track::Read()
{
    assert(m_Inited && m_FileHandle);

    // Create buffer for track (4096 bytes)
    size_t buffer_size = 4096;
    m_BothChannels.resize( buffer_size/sizeof(short) );

    // Read track
    size_t done = 0;
    int err = mpg123_read( m_FileHandle, (unsigned char*)&m_BothChannels[0], buffer_size, &done );

    if (err != MPG123_OK)
        return false;

    // Fill left and right channels
    size_t sizeOfOneChannel = done / ( sizeof(short) * 2);
    m_LeftChannel.resize(sizeOfOneChannel);
    m_RightChannel.resize(sizeOfOneChannel);

    for (size_t i = 0; i < sizeOfOneChannel; ++i)
    {
        m_LeftChannel[i] = m_BothChannels[i * 2];
        m_RightChannel[i] = m_BothChannels[i * 2 + 1];
    }

    // Can continue reading
    return true;
}

///////////////////////////////////////////////////////////////////////////
